<template>
  <q-dialog v-model="visible" persistent>
    <q-card style="max-height: calc(100vh - 3rem)">
      <q-tabs
        v-model="tab"
        active-color="accent"
        align="center"
        indicator-color="accent"
        inline-label
      >
        <q-tab name="basic" label="简化选择器" icon="checklist" />
        <q-tab name="full" label="高级选择器" icon="table_chart" />
      </q-tabs>
      <q-input
        square
        v-if="currentMap !== undefined"
        label="当前地图"
        input-class="text-bold text-primary"
        outlined
        v-model="currentMap.name"
        readonly
      >
        <template v-slot:append>
          <q-btn
            outline
            icon="sync"
            color="primary"
            label="重载"
            @click="chooseMap(currentMap.id)"
            class="text-bold"
          />
        </template>
      </q-input>
      <q-tab-panels v-model="tab" animated>
        <q-tab-panel name="basic" class="q-gutter-y-md">
          <q-select
            outlined
            clearable
            v-model="group"
            :options="groups"
            label="选择地图组"
          />
          <q-select
            label="选择地图"
            outlined
            v-model="selected[0]"
            @filter="filterFn"
            :use-input="!selected"
            clearable
            :options="options"
            @clear="selected = []"
            map-options
            emit-value
            option-label="name"
          >
          </q-select>
        </q-tab-panel>
        <q-table
          name="full"
          style="max-height: calc(100vh - 13rem); overflow: auto"
          class="sticky-header-table no-border-radius"
          :rows="mapOptions"
          selection="multiple"
          row-key="id"
          :columns="columns"
          :filter="filter"
          v-model:selected="selected"
          virtual-scroll
          hide-bottom
          :rows-per-page-options="[0]"
          :virtual-scroll-sticky-size-start="20"
        >
          <template v-slot:top>
            <div class="row full-width q-gutter-y-sm">
              <q-select
                outlined
                dense
                style="min-width: 10rem"
                clearable
                v-model="group"
                v-if="online"
                :options="groups"
                behavior="menu"
                label="地图组筛选"
              />
              <q-space />
              <q-input
                outlined
                dense
                v-model="filter"
                placeholder="关键字筛选"
                clearable
              />
            </div>
          </template>
        </q-table>
      </q-tab-panels>
      <q-separator />
      <div class="row q-gutter-x-sm full-width q-pa-sm">
        <template v-if="selected.length === 1">
          <q-btn
            flat
            color="accent"
            label="修改"
            @click="modifyMap.show(selected[0])"
            class="text-bold"
          />
          <q-btn
            flat
            color="negative"
            label="删除"
            @click="remove"
            class="text-bold"
          />
        </template>
        <q-btn
          flat
          color="negative"
          v-else-if="selected.length > 1"
          label="批量删除"
          class="text-bold"
          @click="remove"
        />
        <template v-else-if="currentMap !== undefined">
          <q-btn
            flat
            color="accent"
            label="修改"
            @click="modifyMap.show(currentMap)"
            class="text-bold"
          />
        </template>
        <q-space />
        <q-btn
          flat
          label="取消"
          color="secondary"
          class="text-bold"
          v-close-popup
        />
        <q-btn
          flat
          :disable="selected.length !== 1"
          color="primary"
          label="确认"
          @click="chooseMap(selected[0].id)"
          class="text-bold"
        />
      </div>
      <q-inner-loading :showing="loadingVisible">
        <q-spinner-gears size="50px" color="primary" />
      </q-inner-loading>
    </q-card>
    <modify-map ref="modifyMap" @update="getMapList" />
  </q-dialog>
</template>

<script>
import { ref, inject, computed, watch } from "vue";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api/index.js";

import ModifyMap from "components/rosMapRemote/map/ModifyMap.vue";

const columns = [
  { name: "name", label: "名称", field: "name", align: "left" },
  { name: "poseCount", label: "点位数量", field: "poseCount", align: "left" },
  { name: "group", label: "分组", field: "group", align: "left" },
  { name: "type", label: "类型", field: "type", align: "left" },
];

export default {
  name: "MapSelector",
  components: { ModifyMap },
  props: {
    remote: { type: Boolean, default: false },
    autoShow: { type: Boolean, default: false },
  },
  setup(props, context) {
    const $q = useQuasar();
    const visible = ref(false);
    const loadingVisible = ref(false);

    const online = inject("online");
    const mapUrl = inject("mapUrl");

    const mapFunction = inject("mapFunction");
    watch(mapFunction, (value) => {
      if (value !== "mapSelector") visible.value = false;
    });

    const mapId = inject("mapId");
    const mapList = ref([]);
    const selected = ref([]); // 当前选中的地图
    const groups = ref([]); // 地图分组的选项
    const group = ref(null); // 地图分组
    const mapOptions = computed(() =>
      (group.value === null
        ? mapList.value
        : mapList.value.filter((item) => item.group === group.value)
      ).filter((item) => item.id !== mapId.value)
    );
    const options = ref([]);

    const currentMap = computed(
      () => mapList.value.filter((item) => item.id === mapId.value)[0]
    );
    // 获取地图列表
    function getMapList(isInit) {
      api
        .get(mapUrl.value + "all/simple", { params: { type: "ros" } })
        .then((rs) => {
          if (rs.status === 200) {
            mapList.value = rs.data;
            if (isInit) {
              setGroup();
            }
          } else {
            $q.notify({ message: "加载地图列表失败", type: "negative" });
          }
          if (online.value) {
            api.get(mapUrl.value + "groups").then((rs) => {
              groups.value = rs.data;
            });
          }
        })
        .catch(() => {
          $q.notify({ message: "加载地图列表失败", type: "negative" });
          if (online.value === true) {
            $q.notify({ message: "尝试使用本地地图", type: "info" });
            online.value = false;
            getMapList();
          }
        });
      loadingVisible.value = false;
    }

    function setGroup() {
      if (currentMap.value !== undefined) {
        if (currentMap.value.group !== "") {
          group.value = currentMap.value.group;
        } else {
          group.value = null;
        }
      }
    }

    function show() {
      mapFunction.value = "mapSelector";
      visible.value = true;
      loadingVisible.value = true;
      mapList.value = [];
      selected.value = [];
      getMapList(true);
    }
    if (props.autoShow) show();

    return {
      tab: ref("basic"),
      modifyMap: ref(),
      columns,
      online,
      group,
      groups,
      visible,
      loadingVisible,
      currentMap,
      selected,
      mapOptions,
      options,
      filter: ref(""),
      getMapList,
      chooseMap(id) {
        // 如果没有id,直接返回
        if (!id) return;
        if (props.remote) {
          mapId.value = id;
          visible.value = false;
          if (currentMap.value !== undefined) {
            group.value = currentMap.value.group;
          }
          context.emit(
            "sameGroup",
            (group.value === null
              ? []
              : mapList.value.filter((item) => item.group === group.value)
            ).filter((item) => item.id !== mapId.value)
          );
        } else {
          loadingVisible.value = true;
          api
            .get(useAPIStore().amrMapUrl + "set/" + id)
            .then((rs) => {
              if (rs.data) {
                visible.value = false;
                $q.notify({ message: "切换地图中", type: "positive" });
              } else {
                $q.notify({ message: "切换地图失败", type: "negative" });
              }
              loadingVisible.value = false;
            })
            .catch((e) => {
              console.log(e);
              $q.notify({ message: "切换地图失败", type: "negative" });
              loadingVisible.value = false;
            });
        }
      },
      remove() {
        if (selected.value.length === 1) {
          $q.dialog({
            title: "删除单张地图",
            message: "是否要删除 " + selected.value[0].name + "?",
            ok: { label: "确定", class: "text-bold", flat: true },
            cancel: {
              label: "取消",
              class: "text-bold",
              color: "secondary",
              flat: true,
            },
            persistent: true,
          }).onOk(() => {
            api
              .delete(mapUrl.value + selected.value[0].id)
              .then(() => {
                loadingVisible.value = true;
                getMapList(); // 刷新列表
                selected.value = [];
                $q.notify({ message: "删除地图成功", type: "positive" });
              })
              .catch((err) => {
                console.error(err);
                $q.notify({ message: "删除地图失败", type: "negative" });
              });
          });
        } else {
          if (selected.value.length === mapOptions.value.length) {
            $q.notify({
              message: "不允许一次性删除所有地图",
              type: "warning",
              position: "top",
            });
          } else {
            $q.dialog({
              title: "批量删除地图",
              message: "是否要删除共" + selected.value.length + "张地图?",
              ok: { label: "确定", class: "text-bold", flat: true },
              cancel: {
                label: "取消",
                class: "text-bold",
                color: "secondary",
                flat: true,
              },
              persistent: true,
            }).onOk(() => {
              api
                .put(
                  mapUrl.value + "/delete",
                  selected.value.map((item) => item.id)
                )
                .then(() => {
                  loadingVisible.value = true;
                  getMapList(); // 刷新列表
                  selected.value = [];
                  $q.notify({ message: "批量删除地图成功", type: "positive" });
                })
                .catch((err) => {
                  console.error(err);
                  $q.notify({ message: "批量删除地图失败", type: "negative" });
                });
            });
          }
        }
      },
      show,
      filterFn(val, update) {
        if (val === "") {
          update(() => {
            options.value = mapOptions.value;
          });
          return;
        }

        update(() => {
          const needle = val.toLowerCase();
          options.value = mapOptions.value.filter(
            (v) => v.name.toLowerCase().indexOf(needle) > -1
          );
        });
      },
    };
  },
};
</script>
